use std::error::Error;
use visa;
use std::ffi::CString;
use libc::{c_int, c_void, c_uint, size_t, strerror};

const IPADDRESS: &str = "192.168.2.56";
const PORT: i32 = 5025;
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Hello, visa!");

    let visa = visa::create(visa::Binary::Default).unwrap();

    let mut _session = 0;
    let status = visa.viOpenDefaultRM(&mut _session);
    if status != 0 {
        return Err("RM not found.".into());
    }
    let address = CString::new(format!("TCPIP0::{IPADDRESS}::{PORT}::SOCKET")).unwrap();
    let mut vi = 0;
    let status = visa.viOpen(_session, address.as_ptr(), 0, 0, &mut vi);
    if status != 0 {
        return Err("viOpen failed".into());
    }
    visa.viSetAttribute(vi, visa::VI_ATTR_TMO_VALUE, 5000); // Set timeout
    visa.viSetAttribute(vi, visa::VI_ATTR_TERMCHAR, 10); // set termination byte to 10
    visa.viSetAttribute(vi, visa::VI_ATTR_TERMCHAR_EN, 1); // enabled termination byte to stop reading when encountering this character.   

    let cmd = b"*IDN?\n";
    let mut ret_cnt = 0u32;
    let status=visa.viWrite(vi,cmd.as_ptr(),u32::try_from(cmd.len()).unwrap(),&mut ret_cnt);
    if status != 0 {
        return Err("viWrite failed".into());
    }
    let resp = vec![0u8; 64];
    let status = visa.viRead(vi, resp.as_ptr() as *mut _, 50, &mut ret_cnt);
    if status == 0 {
        let response = std::str::from_utf8(&resp[0..ret_cnt as usize]).unwrap();
        println!("Response : {}", response);
    }

    Ok(())
}
